﻿using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace UploadControllers
{
    /// <summary>
    /// 上传图片,通过Form表单提交
    /// </summary>
    /// <returns></returns>
    [Route("api/upload")]
    [Authorize]
    public class UpLoadController : ControllerBase
    {
        private readonly IWebHostEnvironment _hostingEnvironment;

        public UpLoadController(IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        [HttpPost]
        public ResultObject Post(IFormFile file)
        {
            List<String> filenames = new List<string>();
            {
                var fileName = file.FileName;
                Console.WriteLine(fileName);

                fileName = $"/Uploads/{fileName}";
                filenames.Add(fileName);

                fileName = _hostingEnvironment.WebRootPath + fileName;

                using (FileStream fs = System.IO.File.Create(fileName))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
            }

            return new ResultObject
            {
                state = "Success",
                resultObject = filenames
            };
        }
    }
    public class ResultObject
    {
        public String state { get; set; }
        public Object resultObject { get; set; }
    }
}

